/** axios封装
 * 请求拦截、相应拦截、错误统一处理
 */
import { notification } from 'antd'
import type { AxiosRequestConfig, AxiosResponse } from 'axios'
import axios from 'axios'
import { cloneDeep } from 'lodash'
import { compile, parse } from 'path-to-regexp'
import store from 'store'

import { history } from '@umijs/max'

const service = axios.create({
  baseURL: '/', // 请求url
  timeout: 30000, // request timeout
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  },
})

// 异常拦截处理器
const errorHandler = (error: any) => {
  const { config } = error
  console.log(config.url + ' failed! ' + error.response.status + ' ' + error.response.statusText)
  if (error.response) {
    if (error.response.status === 401) {
      store.clearAll()
      if (location.pathname !== '/login') {
        history.push({
          pathname: '/login',
          search: `from=${location.pathname} `,
        })
      }
    }
  }
  return Promise.reject(error.response.data)
}

// 请求拦截器
service.interceptors.request.use((config: AxiosRequestConfig) => {
  // 处理动态 url，将 url 中的 :id 替换为对应的参数
  let { url } = config
  const { method = 'GET' } = config
  const opt = ['GET', 'DELETE'].includes(method.toUpperCase()) ? 'params' : 'data'
  const originData = config[opt as 'params' | 'data']
  let cloneData: any = null
  if (Object.prototype.toString.call(originData) !== '[object FormData]') {
    cloneData = cloneDeep(originData)
  } else {
    cloneData = originData
  }
  try {
    let domain = ''
    const urlMatch = url?.match(/[a-zA-z]+:\/\/[^/]*/)
    if (urlMatch) {
      domain = urlMatch[0]
      url = url?.slice(domain.length)
    }

    const match = parse(url || '')
    if (typeof compile === 'function') {
      url = compile(url || '')(originData)
    }

    for (const item of match) {
      if (item instanceof Object && item.name in cloneData) {
        delete cloneData[item.name]
      }
    }
    url = domain + url
  } catch (err) {
    console.log(err)
  }

  config.url = url
  config[opt as 'params' | 'data'] = cloneData

  // kms服务需要apiKey
  // let useAuthSecret = config?.headers?.apiKey || ''
  // if (url.includes('/api/kms/') || url.includes('/api/cipher/')) {
  //   useAuthSecret = config?.headers?.apiKey || store.get('use_auth_secret')
  // }
  // config.headers = {
  //   ...config.headers,
  //   apiKey: useAuthSecret,
  // }

  // const tokenType = 'Bearer'
  const token = store.get('token')
  if (token) {
    if (config.headers) {
      config.headers.Authorization = 'Bearer ' + token
    } else {
      config.headers = {
        Authorization: 'Bearer ' + token,
      }
    }
  }

  return config
}, errorHandler)

// 响应拦截器
service.interceptors.response.use((res: AxiosResponse) => {
  // 单独对文件进行处理
  const { responseType } = res.config

  if (responseType === 'blob') {
    return {
      data: res.data,
      headers: res.headers,
      code: res.status,
    }
  } else if (
    (res.headers['content-type'] && res.headers['content-type'].indexOf('text/plain') !== -1) ||
    res.headers['content-disposition']
  ) {
    return {
      data: res.data,
      headers: res.headers,
      code: res.status,
    }
  } else {
    // 处理返回数据
    return res
  }
}, errorHandler)

// 处理动态 url，将 url 中的 :id 替换为对应的参数
export default service
